from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from rest_framework_jwt.settings import api_settings

from . import models
from .utils import get_user_by_account
import re

class RegisterModelSerializer(serializers.ModelSerializer):
	sms_code = serializers.CharField(write_only=True, help_text='短信验证码', max_length=6, min_length=4)
	token = serializers.CharField(max_length=1024, read_only=True)
	class Meta:
		model = models.User
		fields = ['id', 'username', 'phone', 'password', 'sms_code', 'token']
		extra_kwargs ={
			'id': {'read_only': True},
			'username': {'read_only': True},
			'phone': {'write_only': True},
			'password': {'write_only': True},
		}
	def validate(self, attrs):
		sms_code = attrs.get('sms_code')
		phone = attrs.get('phone')
		password = attrs.get('password')
		if not re.match(r'^1\d{10}', phone):
			raise serializers.ValidationError('手机号格式有误')
		if get_user_by_account(phone):
			raise serializers.ValidationError('该手机号已被注册')
		return attrs
	def create(self, validated_data):
		validated_data.pop('sms_code')
		password = make_password(validated_data.get('password'))
		username = validated_data.get('phone')
		user = models.User.objects.create(phone=username,username=username,password=password)
		jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
		jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

		payload = jwt_payload_handler(user)
		user.token = jwt_encode_handler(payload)
		return user



